package com.tao.power.config;

import com.tao.power.Dao.LoginMapper;
import com.tao.power.Dto.Result;
import com.tao.power.Enums.ErrorEnums;
import com.tao.power.Pojo.User;
import com.tao.power.Service.LoginService;
import com.tao.power.Utils.SystemExceptionNew;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Component
@Aspect
public class AopConfig {

    @Resource
    private LoginService loginService;

    @Pointcut("@annotation(com.tao.power.config.AuthorityAnnotation)")
    public void point() {
    }

    @Around("point() && @annotation(authorityAnnotation)")
    public Result around(ProceedingJoinPoint pjp, AuthorityAnnotation authorityAnnotation) throws Throwable {
        /*获取用户权限code*/
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        List<String> codes = loginService.queryPowerByUser(user.getId());
        /*判断用户权限是否具备该权限,不具备则抛出异常*/
        if (!codes.contains(authorityAnnotation.value())) {
            throw new SystemExceptionNew(ErrorEnums.No_Power.getValue(), ErrorEnums.No_Power.getLabel());
        }
        return (Result) pjp.proceed();
    }
}
